<?php
namespace Todo\Model\Rate;

use Todo\Model\MemoryModel;
use Todo\Service\DictService;
use Todo\Util\ArrayUtil;

class ProjectModel extends MemoryModel
{
    public $tableName = 'rate_project';

    public $_validate = array(
        array('title', 'require', '请输入项目名称'),
        array('tpl_id', 'require', '请选择使用的模板'),
        array('start_time', 'require', '请选择开始时间'),
        array('end_time', 'require', '请选择打结束时间')
    );

    protected $_auto = array(
        array('start_time', '_start_time', self::MODEL_BOTH, 'callback'),
        array('end_time', '_end_time', self::MODEL_BOTH, 'callback'),
        array('tnt_id', 'auto_tnt', self::MODEL_INSERT, 'function')
    );
    protected function _start_time(){
        $datetime = I('post.start_time');
        if(!$datetime) return 0;
        if(is_numeric($datetime)) return $datetime;
        return strtotime($datetime);
    }
    protected function _end_time(){
        $datetime = I('post.end_time');
        if(!$datetime) return 0;
        if(is_numeric($datetime)) return $datetime;
        return strtotime($datetime);
    }

    /**
     * 统计计算
     * @param int $projectId 项目ID
     * @return bool
     */
    public function countScore($projectId){
        $info = $this->keyFind($projectId);
        if(!$info) {
            $this->error = "您选择的项目不存在或已结束！";
            return false;
        }
        set_time_limit(0);
        $results = new ResultsModel();
        $record = new RecordModel();
        $imports = new ImportsModel();
        $levels = DictService::getInstance()->getDict('SCORE_LEVEL');
        if(!$levels['map']){
            $map = array(
                0 => '不及格',
                60 => '及格',
                70 => '中等',
                80 => '良好',
                90 => '优秀'
            );
        }else{
            $map = $levels['map'];
        }
        $users = D('Todo/Rate/User')->where(array('project_id'=>$projectId, 'type'=>'1'))->select();
        if($imports->where(array('project_id'=>$projectId))->find()){//判断是否有线下分数
            $imported = true;
        }else{
            $imported = false;
        }
        $this->startTrans();
        $results->where(array('project_id'=>$projectId))->delete();
        foreach ($users as $user){
            $data = array('project_id'=>$projectId, 'user_id'=>$user['user_id']);

            $scores = $record->where($data)->order('total')->select();

            if($imported) $data['score'] = $imports->where($data)->sum('score'); //导入的分数
            else  $data['score'] = 0;

            $data['people'] = count($scores); //总人数
            if($info['high_how'] == '1'){ //去高去低
                array_shift($scores);
                array_pop($scores);
            }
            $data['score'] += $this->array_avg($scores,'total');//取平均值
            $data['level'] = $this->_level($data['score'], $map);//评分等级
            $data['name'] = $user['name'];
            $data['sort'] = 0;
            $data['tnt_id'] = auto_tnt();
            if(!$results->add($data)){
                $this->rollback();
                $this->error = "保存失败";
                return false;
            }
        }
        $list = $results->where(array('project_id'=>$projectId))->order('score ASC')->select();
        foreach ($list as $i=>$data){
            $data['sort'] = $i+ 1;
            if(!$results->save($data)){
                $this->rollback();
                $this->error = "排名失败";
                return false;
            }
        }
        $this->commit();
        return true;
    }

    /**
     * 评分等级
     * @param float $score 分数
     * @param array $map 评分等级设置
     * @return int|string
     */
    protected function _level($score, $map){
        asort($map);
        $level = 0;
        foreach ($map as $v=>$title){
            if($score > $v) $level = $v;
        }
        return $level;
    }

    /**
     * 数据取平均值
     * @param $list 数组
     * @param $field 取平均值的字段
     * @return float
     */
    protected function array_avg($list, $field){
        if(!$list) return 0;
        $values = array_column($list, $field);
        return array_sum($values) / count($values);
    }
    
}